<template>
  <div class="admin-dashboard">
    <h2>系统管理后台</h2>
    <div class="admin-panel">

      <!-- 会议室管理 -->
        <h3>会议室管理</h3>
        <form @submit.prevent="addRoom">
        
        <!-- 会议室名称 -->
        <div class="form-group">
            <label>会议室名称：</label>
            <input type="text" v-model="newRoom.roomName" placeholder="请输入会议室名称" required />
        </div>

        <!-- 会议室类型 -->
        <div class="form-group">
            <label>会议室类型：</label>
            <select v-model="newRoom.roomType">
            <option value="教室型">教室型</option>
            <option value="圆桌型">圆桌型</option>
            </select>
        </div>

        <!-- 座位数 -->
        <div class="form-group">
            <label>座位数：</label>
            <input type="number" v-model.number="newRoom.seatCount" placeholder="请输入座位数" min="1" required />
        </div>

        <!-- 设备选项 -->
        <div class="form-group">
            <label>设备情况：</label>
            <div class="device-check">
            <label><input type="checkbox" v-model.number.checkbox="newRoom.hasProjector"> 投影仪</label>
            <label><input type="checkbox" v-model.number.checkbox="newRoom.hasSound"> 音响</label>
            <label><input type="checkbox" v-model.number.checkbox="newRoom.hasInternet"> 网络</label>
            </div>
        </div>

        <!-- 每小时价格 -->
        <div class="form-group">
            <label>每小时价格（元）：</label>
            <input type="number" v-model.number="newRoom.pricePerHour" placeholder="请输入每小时价格" required step="0.01" />
        </div>

        <!-- 提交按钮 -->
        <button type="submit">新增会议室</button>
        </form>

      <!-- 会议室列表展示 -->
      <div class="room-list">
        <div v-for="room in rooms" :key="room.id" class="room-card">
          <h3>{{ room.room_name }}</h3>
          <p>类型：{{ room.room_type }}</p>
          <p>座位数：{{ room.seat_count }}人</p>
          <p>设备：
            <span v-if="room.has_projector">投影仪</span>
            <span v-if="room.has_sound">&nbsp;</span>
            <span v-if="room.has_sound">音响</span>
            <span v-if="room.has_internet">&nbsp;</span>
            <span v-if="room.has_internet">网络</span>
          </p>
          <p>价格：{{ room.price_per_hour }}元/小时</p>
          <button @click="deleteRoom(room)">删除</button>
        </div>
      </div>

      <!-- 用户管理 -->
      <h3>用户管理</h3>

      <!-- 分页的用户列表 -->
      <div class="user-list">
        <div v-for="user in paginatedUsers" :key="user.id" class="user-item">
          <p>账号：{{ user.username }} | 角色：{{ user.user_type }} | 状态：{{ user.is_verified ? '已审核' : '待审核' }}</p>
          <button @click="verifyUser(user)">审核通过</button>
          <button @click="freezeUser(user)">冻结账号</button>
        </div>
      </div>

      <!-- 分页控件 -->
      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
        <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
        <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue';
import axios from '../axios';
import { useAutoRefresh } from '../utils/useAutoRefresh';
import { useUserStore } from '../store/UserStore';
import { useWebSocketStore } from '../store/WebSocketStore';

const userStore = useUserStore();

const mockUsers = ref([]);
const newRoom = ref({
  roomName: '',
  roomType: '教室型',
  seatCount: 0,
  hasProjector: 0, // 用 0 / 1 表示有无设备
  hasSound: 0,
  hasInternet: 0,
  pricePerHour: 0
});
const rooms = ref([]); // 存储会议室列表

// 获取会议室列表
const fetchRooms = async () => {
  try {
    const res = await axios.get('/rooms/list');
    rooms.value = res.data.data;
  } catch (error) {
    alert('获取会议室列表失败');
  }
};

// 添加会议室
const addRoom = async () => {
  try {
    await axios.post('/rooms/add', newRoom.value);
    alert('会议室添加成功');
    // 清空表单
    newRoom.value = {
      roomName: '',
      roomType: '教室型',
      seatCount: 0,
      hasProjector: 0,
      hasSound: 0,
      hasInternet: 0,
      pricePerHour: 0
    };
    fetchRooms(); // 刷新会议室列表
  } catch (error) {
    alert(error.response?.data?.error || '添加失败，请重试');
  }
};

// 删除会议室
const deleteRoom = async (room) => {
  if (!confirm(`确定要删除会议室 ${room.room_name} 吗？`)) return;
  try {
    await axios.delete(`/rooms/${room.id}`);
    alert('会议室删除成功');
    fetchRooms(); // 刷新列表
  } catch (error) {
    alert('删除失败，请重试');
  }
};

const currentPage = ref(1);
const pageSize = 5; // 每页显示5个用户

// 获取用户列表
const fetchUsers = async () => {
  try {
    const res = await axios.get('/users/list');
    mockUsers.value = res.data.data;
  } catch (error) {
    alert('获取用户列表失败');
  }
};

let refreshInterval = null;

onMounted(async () => {
  await fetchRooms();
  await fetchUsers();

  useAutoRefresh(async () => {
    await fetchRooms();
    await fetchUsers();
  }, 2000);
});

onUnmounted(() => {
  clearInterval(refreshInterval);
});

// 分页计算属性
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize;
  const end = start + pageSize;
  return mockUsers.value.slice(start, end);
});

const totalPages = computed(() => Math.ceil(mockUsers.value.length / pageSize));

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++;
};

const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--;
};

// 用户新增事件处理
const handleUserCreated = (payload) => {
  mockUsers.value.push(payload.user);
};

// 会议室删除事件处理
const handleRoomDeleted = (payload) => {
  rooms.value = rooms.value.filter(r => r.id !== payload.roomId);
};

onMounted(async () => {
  await fetchRooms();
  await fetchUsers();
});

onMounted(() => {
  const wsStore = useWebSocketStore();
  wsStore.on('server:user-created', handleUserCreated);
  wsStore.on('server:room-deleted', handleRoomDeleted);
});

onUnmounted(() => {
  const wsStore = useWebSocketStore();
  wsStore.off('server:user-created', handleUserCreated);
  wsStore.off('server:room-deleted', handleRoomDeleted);
});

// 审核用户
const verifyUser = async (user) => {
  try {
    await axios.put(`/users/${user.id}/verify`, { isVerified: true });
    alert('用户审核通过');
    // 刷新用户列表
    await fetchUsers();
  } catch (error) {
    alert(error.response.data.error || '审核失败');
  }
};

// 冻结用户
const freezeUser = async (user) => {
  try {
    await axios.put(`/users/${user.id}/verify`, { isVerified: false });
    alert('用户已冻结');
    await fetchUsers();
  } catch (error) {
    alert(error.response.data.error || '冻结失败');
  }
};
</script>

<style scoped>
.admin-dashboard {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 40px;
}

.admin-panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 900px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  /* background-color: #f9fafb; */
}

.device-check {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}
.device-check label {
  font-size: 14px;
}

.form-group {
  width: 180px;
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
}

/* 表单居中 */
form {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  margin-bottom: 30px;
  width: 100%;
  max-width: 400px;
}

input,
select{
  width: 100%;
  padding: 8px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
}

/* 会议室列表居中 */
.room-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
  width: 100%;
}

.room-card {
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  width: 230px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  text-align: center;
}

/* 用户管理区域居中 */
.user-list {
  width: 100%;
  max-width: 600px;
  margin-top: 30px;
  padding: 15px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background-color: #fff;
}

.user-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  border-bottom: 1px solid #e5e7eb;
  padding: 10px 0;
}

.user-item:last-child {
  border-bottom: none;
}

/* 分页控件居中 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>